<?php
namespace app\common\service\distribution;
use app\common\cache\distribution\MemberDistributionCache;
use app\common\model\distribution\MemberDistributionModel;
use app\common\service\setting\SettingStorePlatformService;

/**
 * 分销等级
 */
class MemberDistributionService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'title/s' => null,
        'description/s' => null,
        'is_disable/d' => 0,
        'is_default/d' => 0,
        'code/s' => null,//编码
        'image_id/d' => null,//缩略图
        'distribution_mode/d' => 0,//分销模式：1、一级分销 2、二级分销 3、三级分销 0、不分销
        'setting_store_platform_ids/a' => [],//店铺平台IDS
        'rebate_type/d' => 1,//返佣类型:1、按固定返佣 2、按比例返佣
        'rebate_one/f' => 0,//一级返佣
        'rebate_two/f' => 0,//二级返佣
        'rebate_three/f' => 0,//三级返佣
        'sort/d' => 1,//排序
        'remark/s' =>null,//备注
    ];
    /**
     * 分销等级列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MemberDistributionModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,title,description,is_disable,is_default,create_time,update_time,code,image_id,distribution_mode,setting_store_platform_ids,rebate_type,rebate_one,rebate_two,rebate_three,sort,remark';
        }
        if (empty($order)) {
            $order = ['sort'=>'asc',$pk => 'desc'];
        }
        $with = $append = $hidden = [];
        if (strpos($field, 'image_id') !== false) {
            $with[]   = $hidden[] = 'image';
            $append[] = 'image_url';
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        //店铺平台处理
        $platform_list = SettingStorePlatformService::list($where,0,0, [],'id as value,title as label,is_disable as disable');
        foreach ($list as $key=>$val){
            if(isset($val['setting_store_platform_ids']) && $val['setting_store_platform_ids']){
                $list[$key]['setting_store_platform_ids'] = explode(',',$val['setting_store_platform_ids']);
                $list[$key]['setting_store_platform_titles'] ="";
                foreach ($list[$key]['setting_store_platform_ids'] as $k=>$v){
                    foreach ($platform_list as $pk=>$pv){
                        if($v==$pv['value']){
                            if($list[$key]['setting_store_platform_titles']!=""){
                                $list[$key]['setting_store_platform_titles'] .= ",";
                            }
                            $list[$key]['setting_store_platform_titles'] .= $pv['label'];
                            break;
                        }
                    }
                }
            }else{
                $list[$key]['setting_store_platform_titles'] ="";
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 分销等级信息
     *
     * @param int  $id   分销等级id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MemberDistributionCache::get($id);
        if (empty($info)) {
            $model = new MemberDistributionModel();
            $info = $model->with(['image'])->append(['image_url'])->hidden(['image'])->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('分销等级不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            if ($info['setting_store_platform_ids']){
                $info['setting_store_platform_ids'] = explode(',',$info['setting_store_platform_ids']);
                foreach ($info['setting_store_platform_ids'] as $key=>$val){
                    $info['setting_store_platform_ids'][$key] = (int)$val;
                }
            }else{
                $info['setting_store_platform_ids'] =[];
            }
            MemberDistributionCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 分销等级添加
     *
     * @param array $param 分销等级信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MemberDistributionModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        //字段处理
        if(isset($param['setting_store_platform_ids']) && count($param['setting_store_platform_ids'])>0){
            $param['setting_store_platform_ids'] = implode(',',$param['setting_store_platform_ids']);
        }else{
            $param['setting_store_platform_ids'] =null;
        }
        switch ($param['distribution_mode']){
            case 1:
                $param['rebate_two'] =0;
                $param['rebate_three'] =0;
                break;
            case 2:
                $param['rebate_three'] =0;
                break;
            case 3:
                break;
            default:
                $param['rebate_one'] =0;
                $param['rebate_two'] =0;
                $param['rebate_three'] =0;
                break;
        }
        if(isset($param['is_default']) && $param['is_default']==1){
            $res = $model->where('is_default', 1)->update(['is_default'=>0]);
        }
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 分销等级修改
     *
     * @param int|array $ids   分销等级id
     * @param array     $param 分销等级信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MemberDistributionModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        //字段处理
        if(array_key_exists('setting_store_platform_ids', $param)){
            if(isset($param['setting_store_platform_ids']) && count($param['setting_store_platform_ids'])>0){
                $param['setting_store_platform_ids'] = implode(',',$param['setting_store_platform_ids']);
            }else{
                $param['setting_store_platform_ids'] =null;
            }
        }
//        if(array_key_exists('distribution_mode', $param)){
//            switch ($param['distribution_mode']){
//                case 1:
//                    $param['rebate_two'] =0;
//                    $param['rebate_three'] =0;
//                    break;
//                case 2:
//                    $param['rebate_three'] =0;
//                    break;
//                case 3:
//                    break;
//                default:
//                    $param['rebate_one'] =0;
//                    $param['rebate_two'] =0;
//                    $param['rebate_three'] =0;
//                    break;
//            }
//        }
        if(isset($param['is_default']) && $param['is_default']==1){
            $res = $model->where('is_default', 1)->update(['is_default'=>0]);
        }
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MemberDistributionCache::del($ids);
        return $param;
    }
    /**
     * 分销等级删除
     *
     * @param array $ids  分销等级id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MemberDistributionModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MemberDistributionCache::del($ids);
        return $update;
    }
}
